const HtmlWebpackPlugin = require('html-webpack-plugin');

class inlineSourcePlugin {
  constructor(options){
    this.reg = options.reg
  }
  processTags(tag,compilation){
    let newTag,url;
    if(tag.tagName === 'link' && this.reg.test(tag.attributes.href)){
      newTag = {
        tagName: 'style',
        attributes: {type: 'text/css' }
      }
      url = tag.attributes.href
    }
    if(tag.tagName === 'script' && this.reg.test(tag.attributes.src)){
      newTag = {
        tagName: 'script',
        attributes: {type: 'application/javascript' }
      }
      url = tag.attributes.src
    }
    if(url){
      newTag.innerHTML = compilation.assets[url].source()
      delete compilation.assets[url]
      return newTag
    }
    return tag
  }
  apply(compiler){
    let headTags = [],bodyTags = [];
    compiler.hooks.compilation.tap('inlineSourcePlugin', (compilation)=>{
      HtmlWebpackPlugin.getHooks(compilation).alterAssetTagGroups.tapAsync('HtmlWebpackPlugin',(data,cb)=>{
        // console.log('=====',data);
        data.headTags.forEach(tag => {
          headTags.push(this.processTags(tag,compilation))
        })
        data.bodyTags.forEach(tag => {
          bodyTags.push(this.processTags(tag,compilation))
        })
        cb(null, {...data,headTags,bodyTags})
      })
    })
  }
}

module.exports = inlineSourcePlugin